import { removeRule } from '@/services/ant-design-pro/api';
import {
  createRestaurantTable,
  deleteRestaurantTable,
  getRestaurantAreas,
  getRestaurantTables,
  updateRestaurantTable,
} from '@/services/ant-design-pro/desk';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Drawer, message, Popconfirm } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { FormValueType } from './components/UpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
  const hide = message.loading('正在添加');
  try {
    await createRestaurantTable({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败，请重试。');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('更新中');
  try {
    await updateRestaurantTable(fields.id, {
      tableNo: fields.tableNo,
      seats: fields.seats,
      areaId: fields.areaId,
    });
    hide();

    message.success('编辑成功');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const TableList: React.FC = () => {
  const [dataSource, setDataSource] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      search: false,
      title: '餐桌名称',
      dataIndex: 'name',
    },
    {
      search: false,
      title: '区域',
      dataIndex: 'area',
    },
    {
      search: false,
      title: '人数',
      dataIndex: 'seats',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow({ ...record, tableNo: record.name });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          title="确认删除吗"
          key="delete"
          onConfirm={async () => {
            await deleteRestaurantTable(record.id);
            init();
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const init = async () => {
    const resp = await getRestaurantTables({ page: 1, pageSize: 50 });

    const { list } = resp?.data;
    setDataSource(list);
  };

  const initArea = async () => {
    const resp = await getRestaurantAreas({ page: 1, pageSize: 50 });

    const { list } = resp?.data;

    const options = list.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });

    setAreaList(options);
  };

  useEffect(() => {
    initArea();

    init();
  }, []);

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="key"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        dataSource={dataSource}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
        onLoad={init}
        options={false}
      />
      <ModalForm
        title={'新建'}
        width="400px"
        modalProps={{
          destroyOnClose: true,
        }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.RuleListItem);
          if (success) {
            handleModalOpen(false);
            init();
          }
        }}
      >
        <ProFormText
          label="餐桌名称"
          rules={[
            {
              required: true,
            },
          ]}
          name="tableNo"
        />
        <ProFormSelect label="区域" name="areaId" options={areaList}></ProFormSelect>
        <ProFormDigit label="人数" name="seats" />
      </ModalForm>

      <ModalForm
        title={'编辑'}
        modalProps={{
          destroyOnClose: true,
        }}
        width="400px"
        open={updateModalOpen}
        onOpenChange={(vis) => {
          handleUpdateModalOpen(vis);
          if (!vis) setCurrentRow(undefined);
        }}
        onFinish={async (value) => {
          const success = await handleUpdate({ id: currentRow?.id, ...value });
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            init();
          }
        }}
        initialValues={currentRow}
      >
        <ProFormText
          label="餐桌名称"
          rules={[
            {
              required: true,
            },
          ]}
          name="tableNo"
        />
        <ProFormSelect label="区域" name="areaId" options={areaList}></ProFormSelect>
        <ProFormDigit label="人数" name="seats" />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
